<template>
  <div class="consultation">
    <el-tabs v-model="activeName">
      <el-tab-pane label="手工录入" name="first">
      </el-tab-pane>
      <el-tab-pane label="csv录入" name="second">
        <el-upload
          class="avatar-uploader"
          :action="'/upload'"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
        >
          <i class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-tab-pane>
      <el-tab-pane label="数据源录入" name="third">
        <div style="font-weight: bold;color: red;margin-bottom: 10px;">
          注意：sql语句必须以英文封号;分隔
        </div>

        <div style="color: #666;">
          sql语句示例：insert into table (class, qz, ty, ybdy, dy) values ('学校A', '10', '20', '30', '40')
        </div>
        <el-input
          style="margin-top: 20px;"
          type="textarea"
          :rows="10"
          placeholder="sql语句必须以英文封号;分隔"
          v-model="sql">
        </el-input>
        <div style="width: 100%;display: flex;margin: 20px;">
          <el-button style="margin: auto;" size="mini" @click="handleSQL" type="primary">导入</el-button>
        </div>
      </el-tab-pane>
    </el-tabs>
    
    <el-table v-if="tableData.length" :data="tableData" size="mini" style="width: 100%">
      <el-table-column prop="class" label="学校" width="180">
        <template slot-scope="scope">
          <el-input
            size="mini"
            v-model="scope.row.class"
            placeholder="请输入学校名称"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="qz" label="群众">
        <template slot-scope="scope">
          <el-input-number
            size="mini"
            v-model="scope.row.qz"
          ></el-input-number>
        </template>
      </el-table-column>
      <el-table-column prop="ty" label="共青团员">
        <template slot-scope="scope">
          <el-input-number
            size="mini"
            v-model="scope.row.ty"
          ></el-input-number>
        </template>
      </el-table-column>
      <el-table-column prop="ybdy" label="预备党员">
        <template slot-scope="scope">
          <el-input-number
            size="mini"
            v-model="scope.row.ybdy"
          ></el-input-number>
        </template>
      </el-table-column>
      <el-table-column prop="dy" label="党员">
        <template slot-scope="scope">
          <el-input-number
            size="mini"
            v-model="scope.row.dy"
          ></el-input-number>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            type="danger"
            size="mini"
            @click="minus(scope.row)"
            v-if="tableData.length > 1"
            icon="el-icon-minus"
          ></el-button>
          <el-button
            size="mini"
            @click="addRow"
            type="primary"
            icon="el-icon-plus"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-divider></el-divider>
    <div style="margin: 10px; display: flex">
      <el-form
        style="width: 60%; margin: auto"
        size="mini"
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="180px"
        class="demo-ruleForm"
      >
        <el-form-item label="统计图表分类" prop="type">
          <el-select
            style="width: 100%;"
            v-model="ruleForm.type"
            placeholder="请选择"
          >
            <el-option
              v-for="item in options"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="统计图表标题">
          <el-input v-model="ruleForm.title"></el-input>
        </el-form-item>
        <el-form-item label="图表X轴标题">
          <el-input v-model="ruleForm.x"></el-input>
        </el-form-item>
        <el-form-item label="图表Y轴标题">
          <el-input v-model="ruleForm.y"></el-input>
        </el-form-item>
      </el-form>
    </div>
    <div style="width: 100%; display: flex">
      <el-button @click="createChart" style="margin: 20px auto" type="success"
        >生成图表</el-button
      >
    </div>
    <div id="chart"></div>
  </div>
</template>

<script>
import { getCsv, addExpense } from "../service.js";
import * as echarts from "echarts";
export default {
  name: "home",
  data() {
    return {
      activeName: "first",
      tableData: [
        {
          class: "",
          qz: "",
          ty: "",
          ybdy: "",
          dy: "",
        }
      ],
      options: ["折线图", "柱状图", "饼图", "雷达图"],
      ruleForm: {
        type: "",
        title: "",
        x: "",
        y: "",
      },
      rules: {
        type: [{ required: true, message: "请选择分类", trigger: "change" }],
      },
      chart: {},
      sql: ''
    };
  },
  watch: {
    activeName(to) {
      if (to === 'first') {
        this.tableData = [
          {
            class: "",
            qz: "",
            ty: "",
            ybdy: "",
            dy: "",
          }
        ]
      } else { 
        this.tableData = []
      }
      this.chart.clear()
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.chart = echarts.init(document.getElementById("chart"));
    })
  },
  methods: {
    handleAvatarSuccess(res) {
      getCsv({
        fileName: res.imgName
      }).then(res => {
        if (res.code === 200) {
          let tableData = []
          for (let item of res.data) {
            tableData.push({
              class: item.学校,
              qz: item['群众'],
              ty: item['共青团员'],
              ybdy: item['预备党员'],
              dy: item['党员'],
            })
          }
          this.tableData = tableData
        } else {
          this.$message.error('格式不对')
        }
      })
    },
    addRow() {
      this.tableData.push({
        class: "",
        qz: "",
        ty: "",
        ybdy: "",
        dy: "",
      });
    },
    createChart() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          // 存入数据库
          // addExpense({
          //   userId: 
          // })
          // 绘制图表
          let chartData = this.tableData
          if (this.chart) {
            this.chart.clear()
          }
          let option = {};
          let optionBL = {};
          let xData = ["群众", "共青团员", "预备党员", "党员"];
          let seriesData = [];
          for (let i = 0; i < chartData.length; i++) {
            let obj = {
              data: [
                chartData[i].qz,
                chartData[i].ty,
                chartData[i].ybdy,
                chartData[i].dy,
              ],
              type: this.ruleForm.type === "折线图" ? "line" : "bar",
              smooth: true,
              name: chartData[i].class,
            };
            seriesData.push(obj);
          }
          if (this.ruleForm.type === "折线图") {
            optionBL = {
              xAxis: {
                name: this.ruleForm.x,
                type: "category",
                data: xData,
              },
              yAxis: {
                name: this.ruleForm.y,
                type: "value",
              },
              series: seriesData,
            };

            option = {
              tooltip: {
                trigger: "axis",
              },
              toolbox: {
                feature: {
                  saveAsImage: {}
                }
              },
              ...optionBL,
            };
          } else if (this.ruleForm.type === "柱状图") {
            optionBL = {
              xAxis: {
                name: this.ruleForm.x,
                type: "category",
                data: xData,
              },
              yAxis: {
                name: this.ruleForm.y,
                type: "value",
              },
              series: seriesData,
            };
            option = {
              toolbox: {
                feature: {
                  saveAsImage: {}
                }
              },
              ...optionBL,
            };
          } else if (this.ruleForm.type === "饼图") {
            let datas = [[], [], [], []];
            for (let item of chartData) {
              datas[0].push({
                name: item.class,
                value: item.qz,
              });
              datas[1].push({
                name: item.class,
                value: item.ty,
              });
              datas[2].push({
                name: item.class,
                value: item.ybdy,
              });
              datas[3].push({
                name: item.class,
                value: item.dy,
              });
            }
            option = {
              toolbox: {
                feature: {
                  saveAsImage: {}
                }
              },
              tooltip: {
                trigger: "item",
              },
              series: datas.map(function(data, idx) {
                console.log(idx, chartData);
                var top = idx * 25;
                return {
                  name: xData[idx],
                  type: "pie",
                  radius: [20, 60],
                  top: top + "%",
                  height: "25%",
                  left: "center",
                  width: 400,
                  itemStyle: {
                    borderColor: "#fff",
                    borderWidth: 1,
                  },
                  label: {
                    alignTo: "edge",
                    formatter: "{name|{b}}\n{time|{c} 人}",
                    minMargin: 5,
                    edgeDistance: 10,
                    lineHeight: 15,
                    rich: {
                      time: {
                        fontSize: 10,
                        color: "#999",
                      },
                    },
                  },
                  labelLine: {
                    length: 15,
                    length2: 0,
                    maxSurfaceAngle: 80,
                  },
                  labelLayout: function(params) {
                    const isLeft = 400
                    const points = params.labelLinePoints;
                    // Update the end point.
                    points[2][0] = isLeft
                      ? params.labelRect.x
                      : params.labelRect.x + params.labelRect.width;
                    return {
                      labelLinePoints: points,
                    };
                  },
                  data: data,
                };
              }),
            };
          } else {
            let seriesData = chartData.map(v => {
              return {
                type: 'radar',
                tooltip: {
                  trigger: 'item'
                },
                data: [
                  {
                    value: [v.qz, v.ty, v.ybdy, v.dy],
                    name: v.class
                  }
                ]
              }
            })
            option = {
              tooltip: {
                trigger: "axis",
              },
              toolbox: {
                feature: {
                  saveAsImage: {}
                }
              },
              tooltip: {
                trigger: 'axis'
              },
              radar: {
                indicator: [
                  { name: "群众", max: 1000 },
                  { name: "共青团员", max: 1000 },
                  { name: "预备党员", max: 1000 },
                  { name: "党员", max: 1000 }
                ],
              },
              series: seriesData
            };
          }
          if (this.ruleForm.title) {
            option.title = {
              text: this.ruleForm.title,
            };
          }
          this.chart.setOption(option);
        }
      });
    },
    handleSQL() {
      if (this.sql.includes('；')) {
        this.$message.error('请输入英文的封号 ;')
        return
      }
      let sql = this.sql.split(';')
      let tableData = []
      for (let item of sql) {
        if (item) {
          let str = item.split('values')[1]
          let arr = str.split(',')
          let arrFormat = []
          arr.forEach(v => {
            v = v.trim()
            v = v.replace(/'/g, ''); 
            if (v.includes('(')) {
              v = v.split('(')[1]
            }
            if (v.includes(')')) {
              v = v.split(')')[0]
            }
            arrFormat.push(v)
          })
          tableData.push(arrFormat)
        }
      }
      let tableData2 = []
        for (let item of tableData) {
          tableData2.push({
            class: item[0],
            qz: item[1],
            ty: item[2],
            ybdy: item[3],
            dy: item[4],
          })
        }
        this.tableData = tableData2
    },
    minus(row) {
      let index = this.tableData.findIndex(v => v === row)
      console.log(index)
      this.tableData.splice(index, 1)
    }
  },
};
</script>

<style scoped>
h2 {
  text-align: center;
  margin-top: 20px;
  margin-bottom: 20px;
}
.consultation-block {
  width: 90%;
  margin-left: 5%;
}

.pagination {
  text-align: center;
  margin-top: 20px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 60px;
  height: 60px;
  line-height: 60px;
  border: 1px dashed gray;
  text-align: center;
}
.avatar {
  width: 60px;
  height: 60px;
  display: block;
}
.img-blocks {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.el-icon-circle-close {
  position: absolute;
  top: -5px;
  right: -5px;
  cursor: pointer;
  color: red;
}
#chart {
  width: 80vw;
  margin: 0 auto;
  height: 500px;
  margin-top: 20px;
}
</style>
